<template>
  <div class="ele-body" style="height: 100%">
    <a-card :bordered="false" class="user-message-card" style="height: 100%">
      <div class="ele-cell ele-cell-align-top" style="height: 100%">
        <a-menu v-model:selected-keys="active" mode="inline" @select="changeType(null)">
          <a-menu-item key="all">全部审核</a-menu-item>
          <a-menu-item key="waitToPass">待审核</a-menu-item>
          <a-menu-item key="historyPass">已打回</a-menu-item>
        </a-menu>
        <div class="ele-cell-content" style="height: 100%">
          <!-- 数据表格 -->
          <ele-pro-table
            ref="table"
            row-key="eid"
            :loading="loading"
            :datasource="data"
            :columns="columns"
            v-model:selection="selection"
            :scroll="{x: 'max-content'}"
            @refresh="query" style="height: 100%">
            <template #toolbar>
              <a-space>
                <a-button type="primary" @click="auditPass">审核通过</a-button>
                <a-button type="primary" @click="auditAllPass">全部通过</a-button>

                <a-button type="danger" @click="auditFailBatch">打回订单</a-button>
              </a-space>
            </template>
            <template #state="{ text }">
              <span :class="['ele-text-warning', 'ele-text-success','ele-text-info'][text]">
                {{ ['待审核', '审核通过','打回'][text] }}
              </span>
            </template>
            <template #action="{ record }">
              <a-space>
                <a @click="view(record)">查看</a>
                <a-divider type="vertical" v-if="record.state!==1&&record.state!==2"/>
                <a @click="auditPass(record)" class="ele-text-success" v-if="record.state!==1&&record.state!==2">通过</a>
                <a-divider type="vertical" v-if="record.state!==1&&record.state!==2"/>
                <a-popconfirm title="确定要打回此订单吗？" @confirm="auditFail(record)">
                  <a class="ele-text-danger" v-if="record.state!==1&&record.state!==2">打回</a>
                </a-popconfirm>
              </a-space>
            </template>
          </ele-pro-table>
        </div>

        <!--查看弹窗-->
        <vxe-modal v-model="viewModalShowing" title="查看订单"
                   id="materialOrderViewModal"
                   width="600"
                   min-width="460"
                   min-height="320"
                   :destroy-on-close="true"
                   :lock-view="false" :mask="false"
                   footer
                   show-footer show-zoom resize remember storage transfer dblclickZoom>
          <template #default>
            <MaterialOrderAuditDetail ref="materialOrderAudit-detail" :creatorName="creatorName == null ?'' : creatorName" :orderId="currentId == null ? '0' : currentId"/>
          </template>
        </vxe-modal>
      </div>
    </a-card>
  </div>
</template>


<script>
import {createVNode} from 'vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {MaterialOrderAuditService} from "@/views/restaurant/material/materialOrderAudit/materialOrderAuditService";
import MaterialOrderAuditDetail
  from "@/views/restaurant/material/materialOrderAudit/materialOrderAudit-detail";

export default {
  name: 'UserMessage',
  components: {
    MaterialOrderAuditDetail
  },
  data() {
    return {
      viewModalShowing:false,
      currentId:'',
      creatorName:'',
      // 导航选中
      active: ['all'],
      // 列表显示数据
      data: [],
      // 表格列配置
      columns: [

        {
          key: 'index',
          width: 38,
          customRender: ({index}) => this.$refs.table.tableIndex + index,
          rowClickChecked: true,
          // 行点击选中当单个选中时互斥
          rowClickCheckedIntelligent: false,
        },
        {
          title: '订单编号',
          dataIndex: 'eid'
        },
        {
          title: '总价(元)',
          dataIndex: 'price',
          formatter({cellValue}){
            if(cellValue!==null){
              return cellValue.toFixed(2)
            }
          }
        },
        {
          title: '状态',
          dataIndex: 'state',
          slots: {customRender: 'state'}
        },
        {
          title: '时间',
          dataIndex: 'createDatetime',
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          slots: {customRender: 'action'}
        }
      ],
      // 列表选中数据
      selection: [],
      // 全部数据
      allData: [],
      // 加载状态
      loading: true
    };
  },
  created() {
    console.log(this.selection)
    console.log(JSON.parse(JSON.stringify(this.loading)))

  },
  mounted() {
    const type = this.$route.query.type;
    if (type) {
      this.active = [type];
    }
    this.query();


  },
  methods: {
    /* 查询全部数据 */
    query() {
      this.loading = true;
      console.log(this.$refs.table.tableIndex);
      const queryParams = {filters: {status: "待审核$|$审核通过$|$打回$|$已入库$|$已退货"}}
      // const queryParams = {filters: {status: "!待提交"}}

      queryParams.orderBys=[]
      queryParams.orderBys.push({property: "t0.create_datetime", order: "desc"})
      MaterialOrderAuditService.findMaterialOrders(queryParams).then((res) => {
        this.loading = false;
        this.allData = res.data.datas;
        console.log(this.allData)
        this.allData.forEach((data)=>{
          switch (data.status){
            case '待审核':
              data.state =  0;
              break;
            case '审核通过':
              data.state = 1;
              break;
            case '打回':
              data.state = 2;
              break;
            default:
              data.state = 1;
              break;
          }

          data.price = (data.price!==null)?data.price:0
          data.price = data.price.toFixed(2)
          console.log(data.state)
          switch (data.status){
            case '待审核':
              data.type = 'waitToPass';
              break;
            case '打回':
              data.type = 'historyPass';
          }
          // data.type = (data.status == '待审核')?'waitToPass':'historyPass';
        })
        this.changeType();

        console.log("查询结果"+JSON.stringify(res.data.datas))
      }).catch((e) => {
        this.loading = false;
        this.$message.error(e.message);
        console.log("出错"+JSON.stringify(e))
      });
    },

    /* 切换消息类型 */
    changeType(index) {
      if (index) {
        this.active = [index];
      }
      if (this.active.indexOf('all') !== -1) {
        console.log(this.data)
        this.data = [].concat(this.allData);
      } else {
        this.data = this.allData.filter((d) => this.active.indexOf(d.type) !== -1);
      }
      this.selection = [];
    },
    //通过订单
    auditPass(row){
      console.log(row)
      MaterialOrderAuditService.updateMaterialOrderAudit(row.eid,1).then(res=>{
        console.log(res)
        row.state = 1;
        row.status = '审核通过';
        this.changeType();
        this.query()
        this.$message.success("操作成功")
      }).catch(e=>{
        console.log(e)
        this.$message.error(e.message)
      })
    },
    //打回订单
    auditFail(row){
      console.log(row)
      MaterialOrderAuditService.updateMaterialOrderAudit(row.eid,2).then(res=>{
        console.log(res)
        row.state = 2;
        row.status = '打回';
        this.changeType();
        this.query()
        this.$message.success("操作成功")
      }).catch(e=>{
        console.log(e)
        this.$message.error(e.message)
      })
    },
    /* 查看 */
    view(row) {
      this.currentId = row.eid;
      this.creatorName = row.creatorName;
      console.log(this.creatorName)
      this.viewModalShowing = true;
      // this.$message.info(row);
    },
    /* 批量打回 */
    auditFailBatch() {
      console.log(this.selection)
      if (!this.selection.length) {
        return this.$message.error('请至少选择一条数据');
      }
      this.$confirm({
        title: '提示',
        content: '确定要打回订单吗?',
        icon: createVNode(ExclamationCircleOutlined),
        maskClosable: true,
        onOk: () => {
          this.loading =true;
          this.selection.forEach((d) => {
            MaterialOrderAuditService.updateMaterialOrderAudit(d.eid,2).then(res=>{
              console.log(res)
              d.state = 2;
              d.status = '打回';
            }).catch(e=>{
              console.log(e)
              this.$message.error(e.message)
            })
          });
          this.$message.success("操作成功")
          this.loading =false;
          this.changeType();
        },
        oncomplete:()=>{

        }


      });
    },
    /* 全部通过 */
    auditAllPass() {
      this.$confirm({
        title: '提示',
        content: '确定要全部通过吗?',
        icon: createVNode(ExclamationCircleOutlined),
        maskClosable: true,
        onOk: () => {
          this.allData.forEach((d) => {
            d.state = 1;
          });
          this.changeType();
        }
      });

    }
  },
  watch: {
    $route() {
      const type = this.$route.query.type;
      this.changeType(type || 'all');
    }
  }
}
</script>

<style scoped>
page {
  height: 100%;
}
.user-message-card :deep(.ant-card-body) {
  padding: 0;
  height: 100%;
}

.ant-table-wrapper {
  height: 100%;
}

.user-message-card .ant-menu {
  height: 100%;
  width: 150px;
  padding-top: 16px;
}

.user-message-card .ant-menu + .ele-cell-content {
  padding: 24px;
}

@media screen and (max-width: 768px) {
  .user-message-card .ant-menu {
    display: none;
  }
}
</style>

